package com.yvan.game.merge.freemarker;

import com.yvan.springmvc.ResponseUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.net.URLCodec;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Slf4j
public class RedirectViewJs extends AbstractView {

    private static final URLCodec URL_CODEC = new URLCodec();

    final String body;
    final String contentType;

    @SneakyThrows
    public RedirectViewJs(String url) {

        StringBuilder sb = new StringBuilder();
        sb.append("<script type=\"text/javascript\">");
        sb.append("window.location.href=\"" + url + "\"");
        sb.append("</script>");
        this.body = sb.toString();
        this.contentType = "text/html;charset=utf-8";
    }

    @Override
    protected void renderMergedOutputModel(@SuppressWarnings("rawtypes") Map model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        boolean useGzip = ResponseUtils.isSupportGzip(request);
        try {
            ResponseUtils.writeJSONToResponse(response, ResponseUtils.DEFAULT_ENCODING, this.body, useGzip, false,
                    this.contentType);
        } catch (IOException e) {
            try {
                log.error("error", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException e1) {
                throw new RuntimeException("system error.", e1);
            }
        }
    }
}
